import GenId from "./genId";
// import { mapStores } from "pinia";
import pinia from "../stores/init";
import { useIndexStore } from "../stores/index";
let socket = null;
const indexStore = useIndexStore(pinia);
class SocketConn{
    constructor(){
        this.openSocket();
        this.openStatus = false;
        this.genId = new GenId({ WorkerId: 1 });
    }
    openSocket(){
        let _self = this;
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //指定要连接的服务器地址与端口
            let host = window.location.host;
            var socketUrl = "ws://"+host+"/websocket";
            if (window.location.protocol === "https:") {
                socketUrl = "wss://"+host+"/chat/websocket";//"chatgpt.dlsjfx.com/chat"
            }
            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            try {
                // 实例化WebSocket对象，建立连接
                socket = new WebSocket(socketUrl);
            }catch (e){
                console.error(e);
            }

            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                socket.send("cgtoken:"+localStorage.getItem("TOKEN"));
                _self.openStatus = true;
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                //消息进入后的处理逻辑
                // setMessageInnerHTML(marked.parse(msg.data));
                _self.setMessageInnerHTML(msg.data);
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
                _self.openStatus = false;
            };
            //发生了错误事件
            socket.onerror = function(e) {
                console.log("websocket发生了错误");
                console.log('WebSocket发生错误: ' + e.code)
                console.log(e)
            }

            window.onbeforeunload = function() {
                _self.closeWebSocket();
            }
        }
    }
    sendMessage(sms) {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");

            let params=new Object();
            params.requestId = this.genId.NextId();
            params.message = sms;
            socket.send(JSON.stringify(params));

            indexStore.$patch((state)=>{
                state.replyMap[params.requestId] = {
                    question:sms,
                    answerMessage:""
                }
            });
            // this.setMessageInnerHTML("<br/>我:<br/>"+message+"<br/>");
            // this.setMessageInnerHTML("<span style='color: red:'>OpenAI：<span><br/>");
        }
    }
    setMessageInnerHTML(responseText) {
        if (responseText){
            try {
                let response = JSON.parse(responseText);
                console.log(response);
                if (response){
                    //
                    indexStore.appendAnswerMessage(response.message,response.requestId)

                }
            }catch (e){
                indexStore.appendAnswerMessage(responseText,-1)
            }
        }
    }
    closeWebSocket() {
        socket.close();
        this.openStatus = false;
    }
}
export default SocketConn;
